(function($){
	
	
	function doAtDocReady(element) {
		
		// porta la sidebar all'altezza totale
		$(element).find('.sidebar').height($(document).height());
		
		// select all sulle tabelle
		$(element).find('table th input[type="checkbox"]').change(function() {
			var checked = $(this).is(':checked');
			
			if ($(this).is(':checked')) {
				$('table td input[type="checkbox"]').attr('checked', 'checked');
			} else {
				$('table td input[type="checkbox"]').removeAttr('checked');
			}
			//.maintable 
		});

		// imposta l'hover sulle tabelle
		$(element).find('.PowerIndexUnit table td, .HierarchicalIndexUnit table td').hover(function() {
			$(this).parent().addClass('hover');
		}, function() {
			$(this).parent().removeClass('hover');
		});
		
		
		// imposta il click sulle tabelle
		$(element).find('table td').not('[class~="linkCell"],[class~="checkbox"]').click(function() {
						
			if ($('table tr.hover td input').is(':checked')) {
				$('table tr.hover td input').removeAttr('checked');
			} else {
				$('table tr.hover td input').attr('checked', 'checked');
			}
		});
		
		$(element).find('section[data-collapsible="true"]').each(function() {
			if (!document.collapsible)
				document.collapsible = {};
				
			var id = $(this).attr("id");
			var open = false;
			if (document.collapsible[id]) {
				open = document.collapsible[id];
			}
			
			var $header = $(this).find("> header");
			var $body = $(this).find("> div");
			
			if ($header.size()) {
				var spanClass = "collapse-open";
				if (!open) {
					$body.hide();
					spanClass = "collapse-closed";
				}
				$header.on("click",  {body: $body, header: $header, id: id}, function(e) {
					e.data.body.toggle();
					e.data.header.find("> span").toggleClass("collapse-closed collapse-open");
					document.collapsible[e.data.id] = !document.collapsible[e.data.id];
				});
				
				$('<span>', {
					'class': spanClass
				}).prependTo($header);
			}
			
			document.collapsible[id] = open;
		});

		
	}
	
	$(document).ready(function($) {
	
		doAtDocReady(document);
	  
		if (typeof wr != "undefined") {
			/* Init for ajax update */
			wr.LegacyAjaxPlugin.addContentUpdateListener(function(element) {
				doAtDocReady(element);
			});
		}
		
		
	});
	
})(jQuery);